<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">名称</label>
        <el-input
          v-model="query.name"
          clearable
          placeholder="名称"
          style="width: 185px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <label class="el-form-item-label">实验室</label>
        <el-select
          v-model="query.labId"
          clearable
          style="width: 185px"
          placeholder="实验室"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        >
          <el-option
            v-for="item in labs"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <label class="el-form-item-label">一级授权人</label>
        <el-select
          v-model="query.storehouseAdminId"
          clearable
          style="width: 185px"
          placeholder="一级授权人"
          class="filter-item"
          :remote-method="getName"
          filterable
        >
          <el-option
            v-for="item in auth1UsersList"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
        </el-select>
        <label class="el-form-item-label">二级授权人</label>
        <el-select
          v-model="query.directorId"
          clearable
          style="width: 185px"
          placeholder="二级授权人"
          class="filter-item"
          :remote-method="getName"
          filterable
        >
          <el-option
            v-for="item in auth2UsersList"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="550px" 
      >
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          size="small"
          label-width="100px"
        >
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" style="width: 370px" />
          </el-form-item>
          <el-form-item label="实验室" prop="labId">
            <el-select
              v-model="form.labId"
              style="width: 370px"
              clearable
              filterable
              :remote-method="getLabs"
              :loading="searchLoading"
              placeholder="请选择实验室"
              @change="changeLab(form.labId)"
            >
              <el-option
                v-for="item in labs"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="mac地址" prop="mac">
            <el-input v-model="form.mac" style="width: 370px" />
          </el-form-item>
          <el-form-item label="一级授权人" prop="storehouseAdminId">
            <el-select
              v-model="form.storehouseAdminId"
              style="width: 370px"
              clearable
              filterable
              :remote-method="getName"
              :loading="searchLoading"
              placeholder="请选择一级授权人"
            >
              <el-option
                v-for="item in auth1UsersList"
                :key="item.id"
                :label="item.username"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="二级授权人" prop="directorId">
            <el-select
              v-model="form.directorId"
              style="width: 370px"
              clearable
              filterable
              :remote-method="getName"
              :loading="searchLoading"
              placeholder="请选择二级授权人"
            >
              <el-option
                v-for="item in auth2UsersList"
                :key="item.id"
                :label="item.username"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button
            :loading="crud.status.cu === 2"
            type="primary"
            @click="crud.submitCU"
            >确认</el-button
          >
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="labName" label="实验室" />
        <el-table-column prop="mac" label="mac地址" />
        <el-table-column prop="storeHouseAdminName" label="一级授权人" />
        <el-table-column prop="directorName" label="二级授权人" />
        <!-- <el-table-column prop="createdAt" label="日期" /> -->
        <el-table-column
          v-if="checkPer(['admin', 'cabinet:edit', 'cabinet:del'])"
          label="操作"
          width="240PX"
          align="center"
        >
          <template slot-scope="scope">
            <udOperation :data="scope.row" :permission="permission" />
            <el-button
              size="mini"
              type="success"
              @click="toOpenDoor(scope.row.id)"
              >开门</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="toCloseDoor(scope.row.id)"
              >关门</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import {getAutherIdsAPI} from '@/api/authorization'
import crudCabinet from "@/api/cabinet";
import { openDoor, closeDoor } from "@/api/cabinet";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import rrOperation from "@crud/RR.operation";
import crudOperation from "@crud/CRUD.operation";
import udOperation from "@crud/UD.operation";
import pagination from "@crud/Pagination";
import { get, findAdmin } from "@/api/lab";
import { allNamelist } from "@/api/user";

const defaultForm = {
  id: null,
  name: null,
  labId: null,
  administrator: null,
  createdAt: null,
  updatedAt: null,
  isDeleted: null,
  mac: null,
  storehouseAdminId: null,
  directorId: null,
  type: 1,
};
export default {
  name: "Cabinet",
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({
      title: "化学品柜",
      url: "api/cabinet/chemicalsList",
      idField: "id",
      sort: "id,desc",
      crudMethod: { ...crudCabinet },
      // query: {
      //   type: 1,
      // }
    });
  },
  data() {
    return {
      permission: {
        add: ["admin", "cabinet:add"],
        edit: ["admin", "cabinet:edit"],
        del: ["admin", "cabinet:del"],
      },
      rules: {
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        labId: [
          { required: true, message: "实验室不能为空", trigger: "change" },
        ],
        storehouseAdminId: [
          { required: true, message: "仓库管理员不能为空", trigger: "change" },
        ],
        directorId: [
          { required: true, message: "主任不能为空", trigger: "change" },
        ],
        mac: [{ required: true, message: "mac地址不能为空", trigger: "blur" }],
      },
      queryTypeOptions: [
        { key: "name", display_name: "名称" },
        { key: "labName", display_name: "实验室" },
        { key: "adminName", display_name: "负责人" },
      ],
      searchLoading: false,
      labs: [],
      admins: [],
      searchForm: {
        page: 1,
        size: 1000,
        name: "",
        id: "",
      },
      nameList:[],
      auth1UsersList: [],
      auth2UsersList: [],

    };
  },
  created() {
    this.getLabs();
    this.getAdmins();
    // this.getName();
    this.getAutherIds()
  },
  methods: {
    async getAutherIds(){
      const {data} = await getAutherIdsAPI()
      this.auth1UsersList = data.auth1_users
      this.auth2UsersList = data.auth2_users
    },
    getName(){
      allNamelist().then((response) => {
          this.nameList = response.content;
        })
        .catch((_) => {
          // console.log(response);
        });
    },
    getLabs(query = "") {
      this.searchForm.name = query;
      this.searchLoading = true;
      get()
        .then((response) => {
          this.searchLoading = false;
          this.labs = response;
        })
        .catch((_) => {
          this.searchLoading = false;
        });
    },
    getAdmins(query = "") {
      this.searchForm.name = query;
      this.searchLoading = true;
      findAdmin(this.searchForm)
        .then((response) => {
          this.searchLoading = false;
          this.admins = response;
        })
        .catch((_) => {
          this.searchLoading = false;
        });
    },
    toOpenDoor(id) {
      const loading = this.$loading({
        lock: true,
        text: "远程连接失败，请刷新页面重试...",
        spinner: "el-icon-loading",
        background: "rgba(255,255,255,0.8)",
      });
      openDoor({
        id,
      }).then((response) => {
        loading.close();
        this.$message.success("已开门");
        this.crud.refresh();
        setTimeout(() => {
          closeDoor({
            id,
          });
        }, 20000);
      });
    },
    toCloseDoor(id) {
      const loading = this.$loading({
        lock: true,
        text: "远程连接失败，请刷新页面重试...",
        spinner: "el-icon-loading",
        background: "rgba(255,255,255,0.8)",
      });
      closeDoor({
        id,
      }).then((response) => {
        loading.close();
        this.$message.warning("已关门");
        this.crud.refresh();
      });
    },
    // changeLab(id) {
    //   this.labs.forEach(element => {
    //     if (element.id == id) {
    //       this.form.administrator = element.adminId
    //     }
    //   })
    // },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true;
    },
  },
};
</script>

<style scoped lang="scss">
.el-table ::v-deep td.el-table__cell div {
  display: flex;
  align-items: center;

  .el-button {
    width: 43px;
    height: 28px;
    line-height: 28px;
    text-align: center;
    margin-left: 5px !important;
    padding: 0;
  }
}
</style>
